package shop.core.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 二维码生成器工具类
 */
public class QRcodeUtils {

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static int margin = 1;

    /**
     * 生成二维码（带logo）
     *
     * @param request
     * @param content 生成内容
     * @return 生成二维码路径
     */
    public static String createLogoQrcode(HttpServletRequest request, String content, String logoPath) {
        String rootPath = request.getSession().getServletContext().getRealPath("");
        String qrCodePath = rootPath + "/ueditor/upload/qrCodeImgs";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date nowDate = new Date();
        Random random = new Random();
        int s = random.nextInt(9999);
        String fileName = sdf.format(nowDate) + s + ".png";
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map hints = new HashMap();
            //参数配置
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, margin);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            //生成二维码
            File outputFile = new File(qrCodePath, fileName);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            writeToLogoFile(bitMatrix, "png", outputFile, logoPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String FilePath = "ueditor/upload/qrCodeImgs/" + fileName;
        return FilePath;
    }

    /**
     * 生成二维码
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 输出文件(带logo)
     */
    public static void writeToLogoFile(BitMatrix matrix, String format, File file, String logoPath)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        Graphics2D gs = image.createGraphics();

        int ratioWidth = image.getWidth() * 2 / 10;
        int ratioHeight = image.getHeight() * 2 / 10;
        //载入logo
        Image img = ImageIO.read(new File(logoPath));
        int logoWidth = img.getWidth(null) > ratioWidth ? ratioWidth : img.getWidth(null);
        int logoHeight = img.getHeight(null) > ratioHeight ? ratioHeight : img.getHeight(null);

        int x = (image.getWidth() - logoWidth) / 2;
        int y = (image.getHeight() - logoHeight) / 2;

        gs.drawImage(img, x, y, logoWidth, logoHeight, null);
        gs.setColor(Color.black);
        gs.setBackground(Color.WHITE);
        gs.dispose();
        img.flush();
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    /**
     * 上传微信用户头像到服务器
     */
    public static String getIconByUrl(HttpServletRequest request, String iconUrl) {
        try {
            String rootPath = request.getSession().getServletContext().getRealPath("");
            String iconpath = rootPath + "/ueditor/upload/icon/";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date nowDate = new Date();
            Random random = new Random();
            int s = random.nextInt(9999);
            String icoName = sdf.format(nowDate) + s + ".png";
            URL url = new URL(iconUrl);
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            File file = new File(iconpath);
            if (!file.exists()) {
                file.mkdirs();
            }
            OutputStream os = new FileOutputStream(iconpath + icoName);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            is.close();
            iconUrl = iconpath + icoName;
            return iconUrl;
        } catch (Exception e) {
            return "error";
        }
    }



    /**
     * 生成二维码
     * @param request
     * @param content 生成内容
     * @return  生成二维码路径
     */
    public static String createQrcode(HttpServletRequest request,String content){

        String rootPath=request.getSession().getServletContext().getRealPath("");
        String qrCodePath=rootPath+"/ueditor/upload/qrCodeImgs";
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyyMMddHHmmss" );
        Date nowDate=new Date();
        Random random = new Random();
        int s = random.nextInt(9999);
        String fileName=sdf.format(nowDate)+s+".png";
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map hints = new HashMap();
            //参数配置
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, margin);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            //生成二维码
            File outputFile = new File(qrCodePath,fileName);
            if(!outputFile.getParentFile().exists()){
                outputFile.getParentFile().mkdirs();
            }
            writeToFile(bitMatrix, "png", outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String FilePath="ueditor/upload/qrCodeImgs/"+fileName;
        return FilePath;
    }

    /**
     * 输出文件
     */
    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }
}